from flask import Blueprint, request, jsonify
from app.models import db
from app.models.vehicle import Vehicle
from app.utils.auth import require_permission

vehicles_bp = Blueprint('vehicles', __name__)

@vehicles_bp.route('', methods=['GET'])
@require_permission('vehicle.view')
def get_vehicles():
    """获取车辆列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        search = request.args.get('search', '')
        status = request.args.get('status')
        group_id = request.args.get('group_id', type=int)
        
        query = Vehicle.query.filter_by(is_active=True)
        
        if search:
            query = query.filter(
                db.or_(
                    Vehicle.license_plate.contains(search),
                    Vehicle.brand.contains(search),
                    Vehicle.model.contains(search)
                )
            )
        
        if status:
            query = query.filter_by(status=status)
        
        if group_id:
            query = query.filter_by(group_id=group_id)
        
        pagination = query.paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        return jsonify({
            'vehicles': [vehicle.to_dict() for vehicle in pagination.items],
            'total': pagination.total,
            'pages': pagination.pages,
            'current_page': page
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@vehicles_bp.route('', methods=['POST'])
@require_permission('vehicle.create')
def create_vehicle():
    """创建车辆"""
    try:
        data = request.get_json()
        
        if not data.get('license_plate'):
            return jsonify({'error': '车牌号不能为空'}), 400
        
        # 检查车牌号是否已存在
        if Vehicle.query.filter_by(license_plate=data['license_plate']).first():
            return jsonify({'error': '车牌号已存在'}), 400
        
        vehicle = Vehicle(
            license_plate=data['license_plate'],
            brand=data.get('brand'),
            model=data.get('model'),
            year=data.get('year'),
            vehicle_type=data.get('vehicle_type'),
            capacity=data.get('capacity'),
            fuel_type=data.get('fuel_type'),
            status=data.get('status', 'available'),
            group_id=data.get('group_id')
        )
        
        db.session.add(vehicle)
        db.session.commit()
        
        return jsonify({'vehicle': vehicle.to_dict()}), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@vehicles_bp.route('/<int:vehicle_id>', methods=['PUT'])
@require_permission('vehicle.edit')
def update_vehicle(vehicle_id):
    """更新车辆"""
    try:
        vehicle = Vehicle.query.get_or_404(vehicle_id)
        data = request.get_json()
        
        # 检查车牌号是否已被其他车辆使用
        if 'license_plate' in data and data['license_plate'] != vehicle.license_plate:
            if Vehicle.query.filter_by(license_plate=data['license_plate']).first():
                return jsonify({'error': '车牌号已存在'}), 400
        
        # 更新字段
        for field in ['license_plate', 'brand', 'model', 'year', 'vehicle_type',
                     'capacity', 'fuel_type', 'status', 'group_id', 'is_active']:
            if field in data:
                setattr(vehicle, field, data[field])
        
        db.session.commit()
        
        return jsonify({'vehicle': vehicle.to_dict()}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@vehicles_bp.route('/<int:vehicle_id>', methods=['DELETE'])
@require_permission('vehicle.delete')
def delete_vehicle(vehicle_id):
    """删除车辆"""
    try:
        vehicle = Vehicle.query.get_or_404(vehicle_id)
        
        db.session.delete(vehicle)
        db.session.commit()
        
        return jsonify({'message': '车辆删除成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500
